# -*- encoding: utf-8 -*-
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404

from django.views.decorators.cache import cache_page

from django.db.models import Q

from models import Country, Genre, Group

@cache_page(60 * 15)
def groups(request):
    groups = request.section.groups.select_related().order_by('name')
    genres = Genre.objects.order_by('name')
    countries = Country.objects.order_by('name')
    args = None

    args = dict(request.REQUEST)

    if "country" in args and args['country']:
        country = Country.objects.get(code__exact=args['country'])
        groups  = country.groups.order_by('name')                
        
    if "name_starts_with" in args and args['name_starts_with']:
        groups = groups.filter(name__startswith=args['name_starts_with'][0])
        
    if "genre" in args and args['genre']:
        args['genre'] = int(args['genre'])
        groups = groups.filter(genre=args['genre'])

    return render_to_response('groups/groups.html',
                              {'groups': groups,
                               'countries': countries,
                               'genres': genres,
                               'letters': [chr(a+65) for a in range(26)],
                               'args': args},
                              context_instance=RequestContext(request))

@cache_page(60 * 15)
def group(request):
    group = get_object_or_404(Group, pk=request.object_id)
    
    schedule = group.concerts.all()
    
    return render_to_response('groups/group.html',
                              {'group': group,
                               'schedule': schedule},
                              context_instance=RequestContext(request))
